package com.btex.app.pager;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.btex.app.Config;
import com.btex.app.LoginActivity;
import com.btex.app.OTCSellActivity;
import com.btex.app.R;
import com.btex.app.adapter.OTCSellAdapter;
import com.btex.app.entity.OTCBuyAndSellOrderBean;
import com.btex.app.entity.OTCUserInfo;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.OTCRealNameDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/8/13
 * @time 下午2:29
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */

public class OTCSellFragment extends Fragment {


    @BindView(R.id.otc_recy)
    RecyclerView mOtcRecy;
    Unbinder unbinder;
    @BindView(R.id.otc_fragment_recy)
    SwipeRefreshLayout mOtcFragmentRecy;
    private OTCSellAdapter mOtcSellAdapter;
    public String otcType = "USDT_CNY";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View inflate = inflater.inflate(R.layout.otc_fragment, null);
        unbinder = ButterKnife.bind(this, inflate);

        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }

        return inflate;

    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        initAdapter();

        initData();

        mOtcFragmentRecy.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });
    }

    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mOtcRecy.setLayoutManager(linearLayoutManager);
        mOtcSellAdapter = new OTCSellAdapter(null, getContext());
        mOtcSellAdapter.bindToRecyclerView(mOtcRecy);
        mOtcRecy.setAdapter(mOtcSellAdapter);

    }


    private void initData() {
        if (mOtcFragmentRecy != null) {
            mOtcFragmentRecy.setRefreshing(true);
        }

        int num = (int) ((Math.random() * 9 + 1) * 100000);
        OkGo.<String>get(Config.GET_OTC_ORDERS + "&rnd=" + String.valueOf(num)).tag(this).params("pair", otcType).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {

                String result = response.body().toString();

                if (mOtcFragmentRecy != null) {
                    mOtcFragmentRecy.setRefreshing(false);
                }

                try {
                    JSONObject jsonObject = new JSONObject(result);

                    String code = jsonObject.getString(Config.KEY_CODE);


                    if ("1".equals(code)) {

                        Gson gson = new Gson();
                        OTCBuyAndSellOrderBean otcBuyAndSellOrderBean = gson.fromJson(result, OTCBuyAndSellOrderBean.class);
                        List<OTCBuyAndSellOrderBean.DataBean.BidsBean> bids = otcBuyAndSellOrderBean.getData().getBids();

                        setData(bids);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        });


//
//        RequestParams params = new RequestParams();
//        params.addQueryStringParameter("pair", otcType);
//        params.addHeader("app-version", Config.VERSION);
//        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
//
//        MyApplication.get().send(HttpRequest.HttpMethod.GET, Config.GET_OTC_ORDERS + "&rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                if (mOtcFragmentRecy != null) {
//                    mOtcFragmentRecy.setRefreshing(false);
//                }
//
//                String result = responseInfo.result;
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//
//                    String code = jsonObject.getString(Config.KEY_CODE);
//
//
//                    if ("1".equals(code)) {
//
//                        Gson gson = new Gson();
//                        OTCBuyAndSellOrderBean otcBuyAndSellOrderBean = gson.fromJson(result, OTCBuyAndSellOrderBean.class);
//                        List<OTCBuyAndSellOrderBean.DataBean.BidsBean> bids = otcBuyAndSellOrderBean.getData().getBids();
//
//                        setData(bids);
//
//                    }
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//        });

    }

    private void setData(List<OTCBuyAndSellOrderBean.DataBean.BidsBean> bids) {


        if (mOtcSellAdapter != null) {

            if (bids.size() <= 0) {
                if (mOtcRecy != null) {
                    bids.clear();
                    mOtcSellAdapter.replaceData(bids);
                    mOtcSellAdapter.setEmptyView(R.layout.otc_order_empty);
                }

            } else {
                mOtcSellAdapter.replaceData(bids);
            }


        }


        if (mOtcSellAdapter != null) {
            mOtcSellAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                    OTCBuyAndSellOrderBean.DataBean.BidsBean asksBean = (OTCBuyAndSellOrderBean.DataBean.BidsBean) adapter.getData().get(position);

                    getUserInfo(asksBean);
                }
            });
        }


    }

    private void getUserInfo(final OTCBuyAndSellOrderBean.DataBean.BidsBean asksBean) {

        final MicroAVLIDialog microAVLIDialog = new MicroAVLIDialog(getActivity());
        microAVLIDialog.show();
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.URL_MY_INFO + "rnd=" + String.valueOf(num)).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String reuslt = response.body().toString();

                if (microAVLIDialog != null) {
                    microAVLIDialog.dismiss();
                }
                try {
                    JSONObject jsonObject = new JSONObject(reuslt);

                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
                        Gson gson = new Gson();
                        OTCUserInfo otcUserInfo = gson.fromJson(reuslt, OTCUserInfo.class);
                        String prove_level = otcUserInfo.getData().getProve_level();
                        if (prove_level.equals("C0") || prove_level.equals("C1")) {
                            new OTCRealNameDialog(getActivity(), prove_level).show();
                            return;
                        }
                        if (prove_level.equals("C2")) {
                            startActivity(new Intent(getActivity(), OTCSellActivity.class).putExtra("data", (Serializable) asksBean));
                            return;
                        }


                    } else if (jsonObject.getString(Config.KEY_CODE).equals("-2")) {
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

                if (microAVLIDialog != null) {
                    microAVLIDialog.dismiss();
                }
            }
        });


//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), SharedPreferencesUtil.getSharedPreferences(getActivity()));
//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.URL_MY_INFO + "rnd=" + String.valueOf(num), new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                String reuslt = responseInfo.result.toString();
//
//                microAVLIDialog.dismiss();
//
//
//                try {
//                    JSONObject jsonObject = new JSONObject(reuslt);
//
//                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
//                        Gson gson = new Gson();
//                        OTCUserInfo otcUserInfo = gson.fromJson(reuslt, OTCUserInfo.class);
//                        String prove_level = otcUserInfo.getData().getProve_level();
//
//                        if (prove_level.equals("C0") || prove_level.equals("C1")) {
//
//                            new OTCRealNameDialog(getActivity(), prove_level).show();
//
//                            return;
//                        }
//
//                        if (prove_level.equals("C2")) {
//
//                            startActivity(new Intent(getActivity(), OTCSellActivity.class).putExtra("data", (Serializable) asksBean));
//                            return;
//                        }
//
//
//                    } else if (jsonObject.getString(Config.KEY_CODE).equals("-2")) {
//
//                        startActivity(new Intent(getActivity(), LoginActivity.class));
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//            }
//        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OTCSellFragment(String event) {

        otcType = event;
        initData();
//        if (event.equals("usdt")) {
//
//            otcType = "USDT_CNY";
//            initData();
//
//
//        }
//        if (event.equals("tyd")) {
//
//            otcType = "TYD_TYZ";
//            initData();
//        }


    }


    @Override
    public void onPause() {
        super.onPause();
        OkGo.getInstance().cancelTag(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }
}
